package chapter18;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/3/27 20:15
 */
public class LockingMappedFiles {
    private static FileChannel fc;
    private final int LENGTH = 0x8FFFFFF;

    private static class LockAndModify extends Thread {
        private ByteBuffer buffer;
        private int start, end;

        public LockAndModify(ByteBuffer buffer, int start, int end) {
            this.start = start;
            this.end = end;
            buffer.limit(end);
            buffer.position(start);
            //相当于创建了原始buffer的一个切片，两者共享数据，但是position,mark和limit是独立的
            this.buffer = buffer.slice();
            start();
        }

        @Override
        public void run() {
            try {
                FileLock lock = fc.lock(start, end, false);
                System.out.println("locked " + start + " to " + end);
                while (buffer.position() < buffer.limit() - 1) {
                    buffer.put((byte) (buffer.get() + 1));
                }
                System.out.println("release " + start + " to " + end);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
